import UIKit

func createDelayedBlock() -> (() -> Void) {
	var count = 0
	return {
		count += 1
		print("这个Block已经被调用了\(count)次")
	}
}

print("--0s--")
let delayedBlock = createDelayedBlock()
	// 一段时间后调用这个Block
DispatchQueue.main.asyncAfter(deadline:.now() + 3) {
	print("--3s--")
	delayedBlock()
	delayedBlock()
}


func createStringFormattingBlock() -> ((String, String) -> String) {
	return { (first, second) in
		return "\(first) - \(second)"
	}
}
let formattingBlock = createStringFormattingBlock()
let result = formattingBlock("苹果", "香蕉")
print(result)

//返回值类型不为空的 Block 的应用场景
//数据转换和映射场景：

let numbers = [1, 2, 3, 4, 5]
func transformArray(_ array: [Int], _ transformBlock: (Int) -> Int) -> [Int] {
	var newArray: [Int] = []
	for element in array {
		let transformedElement = transformBlock(element)
		newArray.append(transformedElement)
	}
	return newArray
}
let squareBlock: (Int) -> Int = { number in
	return number * number
}
let squaredNumbers = transformArray(numbers, squareBlock)
print(squaredNumbers)

//返回值类型不为空的 Block 的应用场景
//数据转换和映射场景：
let numbers2 = [1, 2, 3, 4, 5]
func filterArray(_ array: [Int], _ filterBlock: (Int) -> Bool) -> [Int] {
	var newArray: [Int] = []
	for element in array {
		if filterBlock(element) {
			newArray.append(element)
		}
	}
	return newArray
}
let evenNumberBlock: (Int) -> Bool = { number in
	return number % 2 == 0
}
let evenNumbers = filterArray(numbers2, evenNumberBlock)
print(evenNumbers)
